// pages/admin/permission-management/permission-management.js
const { authManager } = require('../../../utils/auth');

Page({
  data: {
    departments: [],
    loading: true,
    expandedDepts: []
  },

  onLoad() {
    // 检查管理员权限
    if (!authManager.pageAdminCheck()) {
      return;
    }
    this.loadDepartmentUsers();
  },

  onShow() {
    // 检查管理员权限
    if (!authManager.pageAdminCheck()) {
      return;
    }
    this.loadDepartmentUsers();
  },

  // 加载部门用户数据
  loadDepartmentUsers() {
    this.setData({ loading: true });

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetDepartmentUsers/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username')
      },
      success: (res) => {
        if (res.data.status) {
          // 预处理部门数据
          const departments = res.data.departments.map(dept => ({
            ...dept,
            isExpanded: this.data.expandedDepts.includes(dept.id),
            users: dept.users.map(user => ({
              ...user,
              avatarText: user.zh_name ? user.zh_name.charAt(0) : '?'
            }))
          }));

          this.setData({
            departments: departments,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 切换部门展开状态
  toggleDepartment(e) {
    const deptId = parseInt(e.currentTarget.dataset.id);
    let expandedDepts = [...this.data.expandedDepts];
    
    const index = expandedDepts.indexOf(deptId);
    if (index > -1) {
      expandedDepts.splice(index, 1);
    } else {
      expandedDepts.push(deptId);
    }
    
    // 更新部门展开状态
    const departments = this.data.departments.map(dept => ({
      ...dept,
      isExpanded: expandedDepts.includes(dept.id)
    }));
    
    this.setData({ 
      expandedDepts: expandedDepts,
      departments: departments
    });
  },

  // 查看用户权限
  viewUserPermissions(e) {
    const userId = e.currentTarget.dataset.userId;
    const userName = e.currentTarget.dataset.userName;
    
    wx.navigateTo({
      url: `/pages/admin/user-permission-detail/user-permission-detail?userId=${userId}&userName=${userName}`
    });
  },

  // 刷新数据
  onRefresh() {
    this.loadDepartmentUsers();
  }
});